package myatoi;

import java.math.BigInteger;

class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().myAtoi("9223372036854775808"));
    }
}

class Solution {
    //0=>48 1=>49 2=>50 3=>51 4=>52 5=>53 6=>54 7=>55 8=>56 9=>57 +=>43 -=>45  空格=>32 .=>46 0 字符串结束符
    public int myAtoi(String s) {
        int sign = 1;
        long res = 0;
        boolean exist = false, noSign = true;
        //去除字符串的前导空格
        s = s.trim();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int n = c;
            //判断正负
            if (noSign) {
                sign = n == 45 ? -1 : 1;
                noSign = !noSign;
            }
            if (n >= 48 && n <= 57) {
                if(!exist)
                exist = !exist;
                n -= 48;
                res *= 10;
                res += n;
            } else {
                if (exist) break;
                if (i == 0 && c != '-' && c != '+') break;
                else if (i == 1 && (n < 48 || n > 57)) break;
            }
            res *= sign;
            if (res > Integer.MAX_VALUE) {
                res = res > Integer.MAX_VALUE ? Integer.MAX_VALUE : res;
                return (int) res;
            }
            if (res < Integer.MIN_VALUE) {
                res = res < Integer.MIN_VALUE ? Integer.MIN_VALUE : res;
                return (int) res;
            }
            res *= sign;
        }
        res *= sign;

        return (int) res;
    }
}